/**
 * Copyright (c) Tapas Mobile.  All Rights Reserved.
 *
 * @author DaiHui 
 * @version 1.0
 */

package com.dotools.utils;

import android.app.ActivityManager;
import android.content.Context;

import com.dotools.debug.LOG;
import com.dotools.hash.HashUtils;

public class ProcessUtils {
    static String sMyProcessName = null;
    static String sMyProcessTag = null;

    public static void ensureMainProcess() {
        if (!getProcessName().equals(Utilities.sMainProcessName)) {
            throw new IllegalStateException("ensureMainProcess: process environment check failed");
        }
    }

    public static String getProcessName() {
        if (ProcessUtils.sMyProcessName != null) {
            return ProcessUtils.sMyProcessName;
        }

        if (Utilities.getApplicationContext() == null) {
            return "unknown";
        }

        if (sMyProcessName == null) {
            int pid = android.os.Process.myPid();
            ActivityManager mActivityManager = (ActivityManager) Utilities.getApplicationContext().getSystemService(
                    Context.ACTIVITY_SERVICE);
            for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
                if (appProcess.pid == pid) {
                    ProcessUtils.sMyProcessName = appProcess.processName;
                    return ProcessUtils.sMyProcessName;
                }
            }
        }

        return "unknown";
    }

    public static String getProcessTag() {
        if (sMyProcessTag == null) {
            sMyProcessTag = HashUtils.getStringMD5(getProcessName()).substring(0, 4);
        }
        return sMyProcessTag;
    }

    public static String getSafeProcessName() {
        String proc = getProcessName();
        return proc.replace(':', '-');
    }

    public static void killSelf() {
        LOG.logD("############################# Good bye, world ...", new Exception());
        LOG.flushLog();

        android.os.Process.killProcess(android.os.Process.myPid());
    }

}
